package com.nosweattechnet.locationsearch;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.nosweattechnet.datatypes.Place;
import com.nosweattechnet.mapmyway.DisplayPlaces;
import com.nosweattechnet.mapmyway.R;
import com.nosweattechnet.server.LocationSearchAsyncTask;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

//Super class for Searching by location
abstract public class SuperLocationSearchActivity extends Activity {
	private double lat;
	private double lon;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Location location=getLocation();
        if(location==null){
        	noLocation();
        }else{
        	lat=location.getLatitude();
        	lon=location.getLongitude();
        }
    }
    
    //Gets the current location of the user using the provider which is best given the Criteria of the subclass
    private Location getLocation(){
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria=getCriteria();
        String locationProvider=locationManager.getBestProvider(criteria,false);
        Location location = locationManager.getLastKnownLocation(locationProvider);
        return location;
    }
    
    abstract protected Criteria getCriteria();    
    
    //Default functionality when the user's location is unknown
    protected void noLocation(){
    	Toast.makeText(this, R.string.noLocation,Toast.LENGTH_LONG).show();
    	finish();
    }
    
    //Searches within the given radius, centered at the latitude and longitude determined from the getLocation function
    protected void radiusSearch(float radius){
    	LocationSearchAsyncTask lsat = new LocationSearchAsyncTask(radius,(float)lat,(float)lon);
    	lsat.execute();
    	ArrayList<Place> p=new ArrayList<Place>();
    	try {
			p=lsat.getPlaces();
		} catch (InterruptedException e) {
		} catch (ExecutionException e) {
		}
    	DisplayPlaces.addPlaces(p);
    	finish();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_super_location_search, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
